//导入router的路由模式
import {createRouter, createWebHistory} from 'vue-router'
// 导入整体布局Layout
import Layout from '@/layout/index.vue'
//导入进度条组件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/index.vue')
    },
    // 配置首页导航并强制跳转仪表盘
    {
        path: '/',
        name: 'Home',
        component: Layout,
        // 重定向跳转到仪表盘
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: '仪表盘',
                icon: 'HomeFilled',
                component: () => import('@/views/dashboard/index.vue')
            }
        ]
    },
    {
        path: '/books',
        name: '图书管理',
        icon: 'Notebook',
        component: Layout,
        children: [
            {
                path: '/books/electronic-book',
                name: '电子书管理',
                icon: 'Document',
                // meta: {requireAuth: true,},
                component: () => import('../views/electronic/index.vue')
            },
            {
                path: '/books/paper-book',
                name: '纸质书籍管理',
                icon: 'Reading',
                component: () => import('../views/paper/index.vue')
            }
        ]
    },
    {
        path: '/404',
        component: () => import('@/views/common/404.vue'),
        meta: {
            title: '404'
        }
    },
    {
        path: '/403',
        component: () => import('@/views/common/403.vue'),
        meta: {
            title: '403'
        }
    },
    //其他路径跳转至404页面
    {
        path: '/:pathMatch(.*)',
        redirect: '/404'
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})


//递增进度条，这将获取当前状态值并添加0.2直到状态为0.994
NProgress.inc(100)
//easing 动画字符串
// speed 动画速度
// showSpinner 进度环显示隐藏
NProgress.configure({easing: 'ease', speed: 600, showSpinner: false})


//router.beforeEach（）一般用来做一些进入页面的限制。比如没有登录，就不能进入某些
// 页面，只有登录了之后才有权限查看某些页面。。。说白了就是路由拦截。
// to 要去到某个页面的属性
// from 从哪个页面来的属性
// next 处理路由跳转及放行
router.beforeEach((to, from, next) => {
    // 启动进度条
    NProgress.start();
    // 判断是否有标题，设置标题头部
    if (to.meta.title) {
        document.title = to.meta.title;
    } else {
        document.title = '图书管理系统';
    }
    const isLogin = store.getters['user/isLogin'];
    // 没有token，强制跳转到登录页
    if (!isLogin && to.path !== '/login') {
        return next({name: 'Login'});
    }
    // 如果当前已经登录且要访问的是登录页面，则跳转到主页
    if (to.path === '/login' && isLogin) {
        next({name: 'Home'});
    }
    next()
});

router.afterEach(() => {
    // 关闭进度条
    NProgress.done()
})

export default router
